package com.example.mystore.service.impl;

import com.example.mystore.mapper.ProductCategoryMapper;
import com.example.mystore.model.ProductCategory;
import com.example.mystore.service.ProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Date;

@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    @Override
    public ProductCategory getProductCategoryById(Integer id) {
        return productCategoryMapper.getProductCategoryById(id);
    }

    @Override
    public List<ProductCategory> getAllProductCategories() {
        return productCategoryMapper.getAllProductCategories();
    }


    @Override
    public ProductCategory addProductCategory(ProductCategory productCategory) {
        // 检查并获取父级分类
        if (productCategory.getParentId() != null) {
            ProductCategory parentCategory = productCategoryMapper.selectById(productCategory.getParentId());
            if (parentCategory == null) {
                throw new IllegalArgumentException("父级分类不存在");
            }
            // 设置新分类的层级
            productCategory.setLevel(parentCategory.getLevel() + 1);
        } else {
            // 如果没有父级分类，则为顶级分类，层级为0
            productCategory.setLevel(0);
            productCategory.setParentId(0); // 将parentId设置为0表示顶级分类
        }

        // 获取同级分类的最大排序值
        Integer maxSortOrder = productCategoryMapper.getMaxSortOrderByParentId(productCategory.getParentId());
        productCategory.setSortOrder(maxSortOrder == null ? 1 : maxSortOrder + 1);

        Date now = new Date();
        productCategory.setCreated(now);
        productCategory.setUpdated(now);


        // 插入新分类
        productCategoryMapper.insertProductCategory(productCategory);
        return productCategory;


    }



    @Override
    public void deleteProductCategory(Integer id) {
        productCategoryMapper.deleteProductCategory(id);
    }


    @Override
    public List<ProductCategory> findParamsByParentId(Integer parentId) {
        return productCategoryMapper.findParamsByParentId(parentId);
    }
    @Override
    public boolean hasSubcategories(Integer id) {
        int count = productCategoryMapper.countSubcategories(id);
        return count > 0;
    }
    @Override
    public boolean hasProducts(Integer id) {
        return productCategoryMapper.countProductsByCategoryId(id) > 0;
    }
    @Override
    public void updateProductCategory(Integer id, String name) {
        Date now = new Date();
        productCategoryMapper.updateProductCategory(id, name,now);
    }

    @Override
    public boolean checkProductCategoryNameExists(String name) {
        return productCategoryMapper.checkProductCategoryNameExists(name) > 0;
    }



}
